import 'package:common_utils/common_utils.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pineapple_flutter/config/config.dart';
import 'package:pineapple_flutter/entity/user_info_entity.dart';
import 'package:pineapple_flutter/provider/userinfo_provider.dart';
import 'package:pineapple_flutter/utils/user_utils.dart';
import 'package:pineapple_flutter/views/dialog_manager.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../http/api.dart';
import '../routers/routers.dart';

class HomeMine extends StatefulWidget {
  const HomeMine({Key? key}) : super(key: key);

  @override
  State<HomeMine> createState() => _HomeMineState();
}

class _HomeMineState extends State<HomeMine> {
  ///
  /// 金刚区的Item
  ///
  Widget getJingangItem(IconData icon, String name, Function() onTap) {
    return InkWell(
      onTap: onTap,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Padding(padding: EdgeInsets.only(top: 56.w)),
          Icon(
            icon,
            size: 42.w,
            color: Colors.white,
          ),
          Text(name,
              style: TextStyle(
                  fontSize: 22.sp, height: 1.8, color: Config.colorWhite)),
        ],
      ),
    );
  }

  Widget getListItem(IconData icon, String title, Function() onTap) {
    return ListTile(
      onTap: onTap,
      leading: Icon(icon, size: 43.w),
      title: Text(title, style: TextStyle(fontSize: 25.w)),
      horizontalTitleGap: 0,
      dense: true,
      iconColor: Config.colorWhite,
      textColor: Config.colorWhite,
      trailing: Icon(Icons.arrow_forward_ios, size: 20.w),
      contentPadding: EdgeInsets.symmetric(vertical: 9.w, horizontal: 0),
    );
  }

  Widget getLoginOutView() {
    UserInfoEntity infoEntity = Provider.of<UserInfoProvider>(context).userInfo;
    if (infoEntity.code == 0) {
      return const Padding(padding: EdgeInsets.all(0));
    } else {
      return Container(
        width: double.infinity,
        height: 98.w,
        padding: EdgeInsets.symmetric(vertical: 0, horizontal: 0.w),
        margin: EdgeInsets.symmetric(vertical: 14.w, horizontal: 35.w),
        child: ElevatedButton(
          onPressed: () {
            DialogManager.showDefaultDialog(context, "确认退出登录吗", () {
              UserUtils.loginOut(context);
            });
          },
          style: ElevatedButton.styleFrom(
            primary: Config.colorMain,
            onPrimary: Config.colorBg,
            shadowColor: Config.colorBg,
            elevation: 0,
            // shape: const StadiumBorder(),
          ),
          child: const Text(
            "退出登录",
            style: TextStyle(color: Config.colorWhite),
          ),
        ),
      );
    }
  }

  ///
  /// 返回用户名的布局，登录与未登录分别返回不同的布局
  ///
  Widget showIsLogin(context) {
    UserInfoEntity infoEntity = Provider.of<UserInfoProvider>(context).userInfo;
    if (infoEntity.code == 200) {
      return Padding(
        padding: EdgeInsets.fromLTRB(25.w, 10.w, 25.w, 0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Text(
              infoEntity.user.nickname,
              style: TextStyle(color: (Config.colorWhite), fontSize: 36.sp),
            ),
            Padding(
              padding: EdgeInsets.all(5.w),
            ),
            Text(
              infoEntity.user.username,
              style: TextStyle(color: (Config.colorWhite), fontSize: 25.sp),
            ),
          ],
        ),
      );
    } else {
      return Padding(
        padding: EdgeInsets.symmetric(vertical: 8.w, horizontal: 25.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            InkWell(
              onTap: () {
                // Future.delayed(const Duration(milliseconds: 1200), () {
                //   setState(() {
                //     bo = true;
                //   });
                // });
                Routes.router.navigateTo(context, Routes.login,
                    transition: TransitionType.inFromRight);
              },
              child: Text(
                '点击登录',
                style: TextStyle(color: (Config.colorWhite), fontSize: 38.sp),
              ),
            ),
          ],
        ),
      );
    }
  }

  ///
  /// 请求个人中心接口
  ///
  getUserInfo(Function onSucces) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? token = prefs.getString("token");
    if (token != null) {
      dynamic users = await Api.getUserinfo();
      Map<String, dynamic> resultUsers = Map.from(users);
      UserInfoEntity infoEntity = UserInfoEntity.fromJson(resultUsers);
      onSucces(infoEntity);
    }
  }

  ///
  /// 判断头像有木有，没有就用本地的占位
  ///
  ImageProvider getHeadImage() {
    UserInfoEntity info = Provider.of<UserInfoProvider>(context).userInfo;
    if (info.code == 200 && info.user.headicon.length > 1) {
      return NetworkImage('${Config.baseUrl}${info.user.headicon}');
    } else {
      return const AssetImage('assets/images/launcher.png');
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getUserInfo((UserInfoEntity infoEntity) {
      Provider.of<UserInfoProvider>(context, listen: false)
          .changeUserinfo(infoEntity);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Config.colorBg,
        width: double.infinity,
        height: double.infinity,
        child: Stack(
          children: [
            Image.asset(
              'assets/images/mine_top_bg.png',
              width: double.infinity,
              height: 390.w,
              fit: BoxFit.fill,
            ),
            Container(
              //头像区
              height: 145.w,
              margin: EdgeInsets.fromLTRB(85.w, 138.w, 0, 0),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  ClipOval(
                    child: Container(
                        width: 145.w,
                        height: 145.w,
                        color: (Config.colorWhite),
                        padding: EdgeInsets.all(3.w),
                        child: CircleAvatar(
                          backgroundImage: getHeadImage(),
                        )),
                  ),
                  showIsLogin(context),
                ],
              ),
            ),
            Container(
              //金刚区
              width: double.infinity,
              height: 175.w,
              padding: EdgeInsets.symmetric(vertical: 0, horizontal: 20.w),
              margin: EdgeInsets.fromLTRB(35.w, 266.w, 35.w, 0),
              decoration: BoxDecoration(
                color: Colors.transparent,
                image: const DecorationImage(
                    image: AssetImage('assets/images/mine_jingang_bg.png'),
                    fit: BoxFit.fill),
                borderRadius: BorderRadius.circular(12.w),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  getJingangItem(Icons.collections, "收藏", () async {
                    if (await UserUtils.isLogin(context) == false) {
                      return;
                    }
                    Routes.router.navigateTo(context, Routes.mineCollect,
                        transition: TransitionType.inFromRight);
                  }),
                  getJingangItem(Icons.comment, "评论", () async {
                    if (await UserUtils.isLogin(context) == false) {
                      return;
                    }
                    Routes.router.navigateTo(context, Routes.mineComment,
                        transition: TransitionType.inFromRight);
                  }),
                  getJingangItem(Icons.add_alert, "消息", () async {
                    if (await UserUtils.isLogin(context) == false) {
                      return;
                    }
                    Routes.router.navigateTo(context, Routes.mineMessage,
                        transition: TransitionType.inFromRight);
                  }),
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.fromLTRB(0, 450.w, 0, 0),
              child: Column(
                children: [
                  Container(
                    //中间列表区
                    width: double.infinity,
                    height: 482.w,
                    padding: EdgeInsets.symmetric(vertical: 0, horizontal: 0.w),
                    margin:
                        EdgeInsets.symmetric(vertical: 15.w, horizontal: 35.w),
                    decoration: BoxDecoration(
                      color: (Config.colorMain),
                      borderRadius: BorderRadius.circular(12.w),
                    ),
                    child: ListView(
                      physics: const NeverScrollableScrollPhysics(),
                      padding:
                          EdgeInsets.symmetric(vertical: 6.w, horizontal: 30.w),
                      children: [
                        getListItem(Icons.person, "个人中心", () async {
                          if (await UserUtils.isLogin(context) == false) {
                            return;
                          }
                          Routes.router.navigateTo(context, Routes.mineInfo,
                              transition: TransitionType.inFromRight);
                        }),
                        const Divider(
                          height: 0.5,
                          color: Config.colorDivider,
                        ),
                        getListItem(Icons.settings, "安全设置", () async {
                          if (await UserUtils.isLogin(context) == false) {
                            return;
                          }
                          Routes.router.navigateTo(context, Routes.mineSetting,
                              transition: TransitionType.inFromRight);
                        }),
                        const Divider(
                          height: 0.5,
                          color: Config.colorDivider,
                        ),
                        getListItem(Icons.feedback, "意见反馈", () async {
                          if (await UserUtils.isLogin(context) == false) {
                            return;
                          }
                          Routes.router.navigateTo(context, Routes.mineFeedback,
                              transition: TransitionType.inFromRight);
                        }),
                        const Divider(
                          height: 0.5,
                          color: Config.colorDivider,
                        ),
                        getListItem(Icons.alternate_email, "关于我们", () {
                          Routes.router.navigateTo(context, Routes.mineAbout,
                              transition: TransitionType.inFromRight);
                        }),
                      ],
                    ),
                  ),
                  getLoginOutView(),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
